class Identity < ActiveRecord::Base
  
  require 'rexml/document'
  require 'net/http'
  #require 'Oos4ruby'
  
  
  belongs_to :user
  has_many :contacts

  validates_uniqueness_of :login, :scope => [:user_id, :service]
  
  def synchronize
     contact_basket = case service
        when 'lastfm'
           lastfm_syncrhonizer(login)
        when 'flickr'
          flickr_synchronizer(login)  
        when '11870'
          oos_synchronizer(login)  
      end
      
      unless contact_basket.empty?
          Contact.delete_all("identity_id = #{id}")
          contact_basket.each do |c|
            contacts.create(c)
          end
        end
        
      generate_connections(service)
        
  end
  

  
  def lastfm_syncrhonizer(user)
    path = '/1.0/user/'+user+'/friends.xml'
    
    @xml = Net::HTTP.start('ws.audioscrobbler.com') do |http|
      req = Net::HTTP::Get.new(path)
      http.request(req).body
    end
    
    basket = []
    REXML::Document.new(@xml).elements.each('//user') do |el|
      c = {}
      c[:username] = el.attributes['username']
      
      el.elements.each('image') do |elimg|
        c[:avatar_url] = elimg.text
      end
      
      el.elements.each('url') do |elurl|
        c[:url] = elurl.text
      end
      
      basket << c
    end
    
    basket
    
  end
  
  def flickr_synchronizer(user)

    basket = []
    flickr = Flickr.new
    user = flickr.users(user)
    contacts = user.contacts
    contacts.each do |co|
      basket << {:username => co.username, :url => co.url}
    end
    basket
  end
  
  def oos_synchronizer(theuser)
    
    oos = Oos4ruby::Oos.new
    oos.auth_app OOS_TOKEN, OOS_PASSWORD
    
    basket = []
    oosuser = oos.user(theuser)
    contacts = oosuser.contacts.entries
    
    contacts.each do |co|
       basket << {:username => co.data.nick, :url => co.data.slug}
    end
    basket
  end
  
  def generate_connections(service)
     #select i.service, u.id as primary_user_id from contacts AS c LEFT JOIN identities AS i ON (c.username = i.login) LEFT JOIN users AS u ON (i.user_id = u.id) where i.login is not null AND user_id != 1;
    
    con = contacts.find_by_sql ["SELECT i.service, u.id AS user_id FROM contacts AS c LEFT JOIN identities AS i ON (c.username = i.login AND i.service = ?) LEFT JOIN users AS u ON (i.user_id = u.id) WHERE i.login IS NOT NULL AND user_id <> ?", service, user_id]
    
    if con
      con.each do |co|
      Connection.create({:left_side_user => user_id, :right_side_user => co.user_id, :service => co.service, :created_at => Time.now }) unless (User.connected?(User.find(user_id), User.find(co.user_id), service))
      end  
    end
    
  
  end
  
end
